/**
 * 统一对uni-app进行封装
 **/ 
import globalData from 'utils/global-data'
import { isEmpty } from 'utils/helper/validator'
import storage from 'utils/helper/storage'
import store from '@/store'
import ajax from '@/api'
import common from './h5/common'
import {mpLogin} from 'api'

export default {
	...(uni || {}),
	/**
	 * 打开地图
	 * @param {Object} params 
	 */
	openMapVC(params={}) {
		let {lat, lng, address, chainName} = params
		uni.openLocation({
			latitude: parseFloat(lat) ,
			longitude: parseFloat(lng),
			name: chainName,
			address,
			fail(res) {
				console.log('[uni.openLocation::fail]', res)
			}
		})
	},
	
	/**
	 * 获取定位城市
	 */
	getLocation() {
    return new Promise((resolve, reject) => {
			console.log('----->准备定位')
			uni.authorize({
				scope: 'scope.userLocation',
				success: function () {
					console.log('----->授权成功')
					uni.getLocation({
						type: 'gcj02',
						success: function (res) {
							console.log('----->定位成功', res)
							resolve(res)
						},
						fail: function (res) {
							reject(res)
						}
					})
				},
				fail: function (res) {
					reject(res)
				}
			})
    })
	},
	/**
   * 获取状态栏高度(px)
   */
  getStatusBarHeight() {
		let defaultHeight = 20
		let menuButtonTop = globalData.get('MenuButtonBoundingClientRectTop')

    if (isEmpty(menuButtonTop)) {
			try {
				menuButtonTop = uni.getSystemInfoSync().statusBarHeight
			} catch(err) {
				menuButtonTop = defaultHeight
			}
		}

		// #ifdef MP-BAIDU
		try {
			const res = uni.getSystemInfoSync()
			menuButton = swan.getMenuButtonBoundingClientRect()
			console.log('============baidu get menuButton', menuButton)
			//苹果手机baidu官方暂时获取不准，手动处理
			if(/ios/i.test(res.platform)){
					if(/iPhone X/i.test(res.model)){
							console.log('===================iPhone X menuButton');
							menuButton = defaultRect;
							menuButton.top = 50;
							menuButton.bottom = 82;
					}else{
							console.log('===================iPhone menuButton');
							menuButton = defaultRect;
					}
			}
		} catch (e) {
				menuButton = defaultRect;
				console.log("error",error,"，手动赋值替代")
		}
		// #endif
		
		if (menuButtonTop >= 0) {
				globalData.set('MenuButtonBoundingClientRectTop', menuButtonTop)
		} else {
				menuButtonTop = defaultHeight
		}
		
    return menuButtonTop
	},

	/**
     * 静默登录
     * @params notCallLogin 若未登录是否强制登录，概念同https://wiki.bestwehotel.com/display/SalesofHotels/BTLoginPlugin的notCallLogin
     */
	login(data) {
		let {notCallLogin = false} = data

		return new Promise((resolve, reject) => {
			// 获取本地缓存token
			let token = storage.get('AUTHORIZATION')
			if (token) {
				store.commit('SAVE_TOKEN', token)
				resolve(token)
				return
			}

			if (notCallLogin) {
				resolve({})
				return
			}

			// 远程静默登录
			uni.showLoading({
				title: '登录中...'
			});
			uni.login({
				success(res) {				
					if (res.code) {
						// 调用登录接口获取token
						mpLogin({
							code: res.code
						}).then(loginResp => {
							store.commit('SAVE_TOKEN', loginResp.result)
							uni.showToast({
								title: '登录成功，请继续操作~',
								icon: 'none',
								duration: 2000
							})
							resolve(loginResp.result)
						}).catch(loginResp => {
							reject(loginResp)
						})
					} else {
						reject()
					}
				},
				complete(res) {
				}
			})
		})
	},
	/**
     * 拨号
     * @param {*} phoneNumber 
     */
	callPhone({phoneNumber}={}) {
		let res = uni.getSystemInfoSync()
		if (/ios/i.test(res.platform)) {
			uni.makePhoneCall({
				phoneNumber: phoneNumber
			})
		} else { // 安卓设备需要弹框询问是否真的要拨号
			uni.showModal({
				title: '确定呼叫以下号码？',
				content: phoneNumber,
				success(res) {
					if (res.confirm) {
						uni.makePhoneCall({
							phoneNumber: phoneNumber
						})
					}
				}
			})
		}
	},

    // 复制
	setClipboardData(data) {
		return new Promise((success, fail) => {
			uni.setClipboardData({ data, success, fail });
		  })
	},
	getClipboardData() {
		return new Promise((success, fail) => {
			uni.getClipboardData({ data, success, fail });
		  })
	},
	/**
	 * 注册账号
	 */
	// register() {
	// 		uni.navigateTo({
	// 				url: '/pages/my/register/index'
	// 		})
	// 		let globalData = getApp().globalData
	// 		return new Promise((resolve, reject) => {
	// 				globalData.registerResolve = (...args) => {
	// 						resolve && resolve.apply(null, args)
	// 				}
	// 		})
	// },
  getOffset: common.getOffset,
  getAllOffset: common.getAllOffset,
	selectCity: common.selectCity,
	getSelectCity: common.getSelectCity,
	getSafeAreaHeight: common.getSafeAreaHeight
	/**
   * 获取自定义导航高度（弃用，因为小程序的选择器不支持子组件内节点查询）
	 * 若要获取自定义导航高度，请在业务部分调用getOffset方法，在组件上包裹一层class
   */
  // async getNavHeight() {
  //   let navOffest = await this.getOffset('.uni-navbar__content', '.uni-navbar')
  //   console.log('getNavHeight', navOffest.height)
  //   return navOffest.height
  // }
}